package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Service
public class UserInfoService {
    @Autowired
    UserService userService;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    FaceEngineService faceEngineService;
    @Autowired
    PicUploadService picUploadService;

    public Boolean saveUserInfo(Map<String, String> param, String token) {
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));
        return this.userInfoMapper.insert(userInfo) == 1;

    }

    public Boolean saveUserLogo(MultipartFile file, String token) {
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return false;
        }
        try {
            boolean b = faceEngineService.checkIsPortrait(file.getBytes());
            if (!b) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        PicUploadResult result = picUploadService.upload(file);
        if(StringUtils.isEmpty(result.getName())){
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        int update = userInfoMapper.update(userInfo, queryWrapper);
        return update==1;
    }
}
